import { useCallback, useMemo, useState } from "react";
import type { ToDoItemType } from "../../types";
import Header from "../header";
import DoList from "../dolist";
import styles from "./style.module.css";
import CurrentTime from "../curentTime";

const TodoList = () => {
  const [todos, setTodos] = useState<ToDoItemType[]>([
    {
      id: 1,
      title: "吃饭",
      completed: false,
    },
    {
      id: 2,
      title: "睡觉",
      completed: true,
    },
    {
      id: 3,
      title: "打游戏",
      completed: false,
    },
  ]);

  const todosList = useMemo(() => {
    return todos.filter((v) => v.completed);
  }, [todos]);

  const notTodosList = useMemo(() => {
    return todos.filter((v) => !v.completed);
  }, [todos]);


  const handleAddClick = useCallback((value: string) => {
    if (value.trim()) {
      setTodos([...todos, { id: Date.now(), title: value, completed: false }]);
    }
  }, [todos])

  const handleDeleteClick = (id: number) => {
    setTodos(todos.filter((v) => v.id !== id));
  };

  const handleSwitchState = (id: number) => {
    setTodos(
      todos.map((item) =>
        item.id === id ? { ...item, completed: !item.completed } : item
      )
    );
  };

  return (
    <div className={styles.container}>
      <CurrentTime></CurrentTime>
      <h1 className={styles.title}>TodoList</h1>
      <Header handleAddClick={handleAddClick} />
      <DoList
        title="待办事项"
        data={notTodosList}
        handleDeleteClick={handleDeleteClick}
        handleSwitchState={handleSwitchState}
      />
      <DoList
        title="已完成事项"
        data={todosList}
        handleDeleteClick={handleDeleteClick}
        handleSwitchState={handleSwitchState}
      />
    </div>
  );
};

export default TodoList;
